package com.example.userdepartment.controller;

import com.example.userdepartment.entity.Department;
import com.example.userdepartment.entity.User;
import com.example.userdepartment.service.DepartmentService;
import com.example.userdepartment.service.UserService;
import com.example.userdepartment.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理控制器
 */
@RestController
@RequestMapping("/api/departments")
public class DepartmentController {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);

    @Autowired
    private DepartmentService departmentService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取所有部门
     */
    @GetMapping
    public Result<List<Department>> getAllDepartments() {
        return Result.success(departmentService.findAll());
    }

    /**
     * 搜索部门
     */
    @GetMapping("/search")
    public Result<List<Department>> searchDepartments(
            @RequestParam(required = false) String keyword) {
        logger.info("搜索部门 - 关键字: {}", keyword);
        List<Department> departments = departmentService.searchDepartments(keyword);
        return Result.success(departments);
    }

    /**
     * 根据ID获取部门
     */
    @GetMapping("/{id}")
    public Result<Department> getDepartmentById(@PathVariable Integer id) {
        Department department = departmentService.findById(id);
        if (department != null) {
            return Result.success(department);
        }
        return Result.error("部门不存在");
    }

    /**
     * 根据部门ID获取部门及其下所有用户
     */
    @GetMapping("/{id}/with-users")
    public Result<Department> getDepartmentWithUsersById(@PathVariable Integer id) {
        Department department = departmentService.findWithUsersById(id);
        if (department != null) {
            return Result.success(department);
        }
        return Result.error("部门不存在");
    }

    /**
     * 获取部门下的所有用户
     */
    @GetMapping("/{id}/users")
    public Result<List<User>> getUsersByDepartmentId(@PathVariable Integer id) {
        return Result.success(userService.findByDepartmentId(id));
    }

    /**
     * 添加部门
     */
    @PostMapping
    public Result<Department> addDepartment(@RequestBody Department department) {
        return Result.success("添加成功", departmentService.add(department));
    }

    /**
     * 更新部门
     */
    @PutMapping("/{id}")
    public Result<Department> updateDepartment(@PathVariable Integer id, @RequestBody Department department) {
        department.setId(id);
        return Result.success("更新成功", departmentService.update(department));
    }

    /**
     * 删除部门
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteDepartment(@PathVariable Integer id) {
        boolean success = departmentService.delete(id);
        if (success) {
            return Result.success("删除成功", null);
        }
        return Result.error("删除失败");
    }

    /**
     * 批量删除部门
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteDepartments(@RequestBody List<Integer> ids) {
        boolean success = departmentService.batchDelete(ids);
        if (success) {
            return Result.success("批量删除成功", null);
        }
        return Result.error("批量删除失败");
    }

    /**
     * 导出部门Excel
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportDepartments() {
        byte[] excelBytes = departmentService.exportDepartments();
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "departments.xlsx");
        
        return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
    }
} 